package com.ojoin.ojoin.eb_spider.service.catchdata;

import com.ojoin.ojoin.eb_spider.dao.PhysicalEaminationMapper;
import com.ojoin.ojoin.eb_spider.domain.AssistCatchData;
import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.model.PhysicalEamination;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.Config;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.paynow.ThreeDESEncryptProvider;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformInfo;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 *
 *
 *
 */

@Service
public class CiMingDataCatchServiceImpl extends SLDataCatchBaseServiceImpl {

    /**
     * 线程内共享Connection，ThreadLocal通常是全局的，支持泛型
     */
    private static ThreadLocal<Set<String>> names = new ThreadLocal<Set<String>>();

    private static Logger log = LoggerFactory.getLogger(CiMingDataCatchServiceImpl.class);

    private final static String personRptUrl = "http://book.ciming.com/hr/getPersonRpt.html?ajax=yes&needUpdate=00&guideBarcode=";
    private final static String downloadReportUrl = "http://book.ciming.com/hr/downloadReport.html";

    @Autowired
    private PhysicalEaminationMapper physicalEaminationMapper;

    @Override
    public boolean LoginByUserInfo(String baseUrl, String username, String password) throws Exception {
        // 开始登陆
        //try {
        this.getWebDriver().get("http://book.ciming.com/hr/BJZXYBKJ");
        this.getWebDriver().sendKeys("id", "principalUserName", username);
        this.getWebDriver().sendKeys("id", "principalPassword", password);


        WebElement verifyE = this.getWebDriver().findElement(WebDriverService.xpath,
                "//*[@id=\"imageCaptcha\"]");
        String code = this.getWebDriver().getVerifyCodeByDMV3(verifyE);

        this.getWebDriver().sendKeys(WebDriverService.ID, "authcode",
                code.toLowerCase());

        this.getWebDriver().click("id", "surbtn");

		/*} catch (Exception e) {
                        log.error(" ", e);

		}*/

        return this.getWebDriver().getDriver().getCurrentUrl().startsWith("http://book.ciming.com/physicalExaTotal.html");
    }

    public void initDownloadDir() {

        String mapping_download_dir = getDownLoadFile();

        this.getAssistCatchData().setDownloadDir(mapping_download_dir);

        LogUtils.info(log, "下载路径download.dir 映射目录-->" + mapping_download_dir);
    }

    public String getDownLoadFile() {
        String mapping_download_dir = null;

        mapping_download_dir = System.getProperties().getProperty("user.home") + File.separator + "Downloads"
                + File.separator + this.getAssistCatchData().getStartMess().getPlatformUser().getPlatformName()
                + File.separator + TimeUtils.getCurDate()
                + File.separator + this.getAssistCatchData().getStartMess().getPlatformUser().getUsername()

        ;

        return mapping_download_dir;

    }

    public String getInitDownLoadFile() {
        String mapping_download_dir = null;

        mapping_download_dir = System.getProperties().getProperty("user.home") + File.separator + "Downloads"
                + File.separator + this.getAssistCatchData().getStartMess().getPlatformUser().getPlatformName()
                + File.separator + this.getAssistCatchData().getStartMess().getPlatformUser().getUsername();

        return mapping_download_dir;

    }
    /**
     * 对密码解密
     *
     * @return
     */
    public String getLoginPassword(String pwd) {
        return pwd;
    }


    @Override
    public void catchData(AssistCatchData assistCatchData) throws Exception {

        try {
            super.init(assistCatchData);
            prepareCatchData();

            boolean flag = isLoginSuccess();

            if (flag) {
                doit();
            }

        } catch (Exception e) {
            LogUtils.error(log, e);
            throw e;

        } finally {
            // 需要确定文件已经下载完毕


            closeCatchData(false, false);
        }
    }

    @Override
    public String catchSupplierName() throws BusinessException {
        initCompanyInfomation();
        String name = "";

        return name;
    }

    public void doit() throws Exception {
        search();
        dealTable();
    }

    public void search() {
        // 设置订单信息
        this.getWebDriver().click(WebDriverService.ID, "orderIdSelect");
        this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"orderIdSelect\"]/option[2]");

        // 设置时间
        this.getWebDriver().sendKeys(WebDriverService.ID, "startDate", TimeUtils.getDateBefore(90));
        this.getWebDriver().sendKeys(WebDriverService.ID, "endDate", TimeUtils.getCurDate());
        //设置状态
        this.getWebDriver().click(WebDriverService.ID, "status");
        this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"status\"]/option[2]");

        // 点击查询
        this.getWebDriver().click(WebDriverService.ID, "queryRpt");

    }

   /* public List<String> dealTable(){
        boolean flag;
        List<String> urls = new ArrayList<>();

        do{
            WebElement table = this.getWebDriver().findElement(WebDriverService.ID,"checkdetail");

            List<WebElement>  trs = this.getWebDriver().findElements(table,WebDriverService.CSS,"tbody tr");

            if(null != trs){
                for(WebElement tr:trs){
                    List<WebElement> tds = this.getWebDriver().findElements(tr,WebDriverService.CSS,"td");
                    //获取报告状态
                    if(this.getWebDriver().IsExist(tds.get(11),WebDriverService.CSS,"span")){
                        WebElement span = this.getWebDriver().findElement(tds.get(11),WebDriverService.CSS,"span");
                        if(span.getText().equals("未查看")){
                            String userid = span.getAttribute("userid");
                            String url = personRptUrl+userid;
                            urls.add(url);
                        }
                    }
                }
            }

            flag=  this.getWebDriver().IsDisplayed(WebDriverService.ID,"downA");
        }while(flag);

        return urls;
    }*/


    public List<String> dealTable() throws Exception {
        List<String> urls = new ArrayList<>();
        try{
            boolean flag;
            do {
                WebElement table = this.getWebDriver().findElement(WebDriverService.ID, "checkdetail");

                List<WebElement> trs = this.getWebDriver().findElements(table, WebDriverService.CSS, "tbody tr");

                if (null != trs) {
                    for (WebElement tr : trs) {
                        List<WebElement> tds = this.getWebDriver().findElements(tr, WebDriverService.CSS, "td");
                        //获取报告状态
                        if (this.getWebDriver().IsExist(tds.get(11), WebDriverService.CSS, "span")) {
                            WebElement span = this.getWebDriver().findElement(tds.get(11), WebDriverService.CSS, "span");
                            //未查看
                            if (span.getText().equals("未查看")) {
                                String userid = span.getAttribute("userid");
                                span.click();
                                //TODO 需要等待弹出下载框
                                this.getWebDriver().waitVisibilityOfElementLocated(WebDriverService.xpath, "//*[@id=\"RptShowList\"]/table/tbody/tr/td[3]/a[2]",60*5);
                                // 点击保存
                                this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"RptShowList\"]/table/tbody/tr/td[3]/a[2]");
                                // 关闭
                               this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"RptShowList\"]/span");
                                // 判断文件是否下载成功
                                File downloadFileDir = new File(getDownLoadFile());

                                File file = DownloadUtils.waitFileDownloadOver(downloadFileDir,
                                        ".*"+userid+".html");
                                //this.getWebDriver().execJavaScript()

                                PhysicalEamination pe = new PhysicalEamination();
                                pe.setAppointmentdate(tds.get(7).getText());
                                pe.setCarded(tds.get(6).getText());
                                pe.setCompanyId(this.getAssistCatchData().getStartMess().getPlatformUser().getUsername());
                                pe.setNumid(userid);
                                pe.setSex(tds.get(3).getText());

                                pe.setUsername(tds.get(2).getText());
                                pe.setId(userid);

                                if(null == file){
                                    pe.setStatus(1);
                                    LogUtils.info(log,"file:--------->" + userid+"下载失败");
                                }else {
                                    pe.setStatus(2);
                                    LogUtils.info(log,"file:--------->" + userid+"下载成功");
                                }
                                physicalEaminationMapper.insert(pe);
                            }
                        }
                    }
                }

                flag = this.getWebDriver().IsDisplayed(WebDriverService.ID, "downA");
                if(flag){
                    LogUtils.info(log,"下一页");
                    this.getWebDriver().click(WebDriverService.ID, "downA");
                }

            } while (flag);

        }catch (Exception e){
            log.error("",e);
        }


        return urls;
    }

    /*public List<String> getDownloadUrl(List<String> urls){
         List<String> downUrls = new ArrayList<>();
         if(null != urls){
            for(String url:urls){
                this.getWebDriver().get(url);
                String html = this.getWebDriver().getDriver().getPageSource();
                CiMingResponse res = JSONUtils.parseObject(html,CiMingResponse.class);
                List li = JSONUtils.parseObject(res.getData(),List.class);
                if(null != li && li.size() > 0){
                    String prt = (String)li.get(0);
                    LogUtils.info(log,prt);
                    PersonRpt personRpt = JSONUtils.parseObject(res.getData(),PersonRpt.class);


                }
            }
        }

        return downUrls;
    }
*/

    public void init() {

    }


    public void initCompanyInfomation() {

        // http://b2bi.gome.com.cn/gmol/sellVatInvQry/detail.hlt?invid=2041525

    }


    @Override
    public boolean getUnpayAccountData() throws BusinessException {
        return true;

    }

    @Override
    public boolean getInstoreOrderData() throws BusinessException {

        return true;
    }

    @Override
    public boolean getOutstoreOrderData() throws BusinessException {
        // 送货记录
        // 对账单
        return true;
    }

    @Override
    public boolean getPayAccountData() throws BusinessException {
        return true;
    }

    @Override
    public BankCardCheck catchSupplierAccount() throws BusinessException {
        // TODO Auto-generated method stub
        return null;
    }

}
